package com.utils;

import com.base.Constants;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HTMLUtil {


    /**
     * 获取指定URL的所有favicon图标地址
     */
    public Map<Constants,Object> getFaviconUrlsAndDescription(String url) {

        Map<Constants,Object> map = new HashMap<Constants,Object>();

        String description = "";
        List<String> faviconUrls = new ArrayList<>();
        URL baseUrl;

        // 校验并解析基础URL
        try {
            baseUrl = new URL(url);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("无效的URL格式: " + e.getMessage());
        }

        // 1. 检查默认路径（根目录下的favicon.ico）
        String defaultFavicon = baseUrl.getProtocol() + "://" + baseUrl.getHost() + "/favicon.ico";
        if (isUrlValid(defaultFavicon)) {
            faviconUrls.add(defaultFavicon);
        }

        // 2. 从HTML的link标签中解析图标（支持png、svg等现代格式）
        try {
            // 模拟浏览器请求，避免被反爬
            Document doc = Jsoup.connect(url)
                    .timeout(10000) // 10秒超时
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
                    .followRedirects(true)
                    .header("Referer", "")  // 设置Referer为空字符串
                    .get();

            // 查找所有rel属性包含"icon"的link标签（如rel="icon"、rel="shortcut icon"）
            Elements iconLinks = doc.select("link[rel*=icon]");
            for (Element link : iconLinks) {
                String href = link.attr("href");
                if (href.isEmpty()) continue;

                // 处理相对路径（转换为完整URL）
                String fullUrl = resolveUrl(baseUrl, href);
                if (!faviconUrls.contains(fullUrl)) {
                    faviconUrls.add(fullUrl);
                }
            }

            Element descriptionMetaElement = doc.select("meta[name=description]").first();
            if(descriptionMetaElement!=null){
                description = descriptionMetaElement.attr("content");
            }

        } catch (IOException e) {
            throw new RuntimeException("获取网页内容失败: " + e.getMessage());
        }

        map.put(Constants.Description,description);
        map.put(Constants.Favicon   ,faviconUrls);
        return map;
    }

    /**
     * 获取指定URL的所有favicon图标地址
     */
    public List<String> getFaviconUrls(String url) {
        List<String> faviconUrls = new ArrayList<>();
        URL baseUrl;

        // 校验并解析基础URL
        try {
            baseUrl = new URL(url);
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("无效的URL格式: " + e.getMessage());
        }

        // 1. 检查默认路径（根目录下的favicon.ico）
        String defaultFavicon = baseUrl.getProtocol() + "://" + baseUrl.getHost() + "/favicon.ico";
        if (isUrlValid(defaultFavicon)) {
            faviconUrls.add(defaultFavicon);
        }

        // 2. 从HTML的link标签中解析图标（支持png、svg等现代格式）
        try {
            // 模拟浏览器请求，避免被反爬
            Document doc = Jsoup.connect(url)
                    .timeout(10000) // 10秒超时
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
                    .followRedirects(true)
                    .get();

            // 查找所有rel属性包含"icon"的link标签（如rel="icon"、rel="shortcut icon"）
            Elements iconLinks = doc.select("link[rel*=icon]");
            for (Element link : iconLinks) {
                String href = link.attr("href");
                if (href.isEmpty()) continue;

                // 处理相对路径（转换为完整URL）
                String fullUrl = resolveUrl(baseUrl, href);
                if (!faviconUrls.contains(fullUrl)) {
                    faviconUrls.add(fullUrl);
                }
            }

        } catch (IOException e) {
            throw new RuntimeException("获取网页内容失败: " + e.getMessage());
        }

        return faviconUrls;
    }

    /**
     * 检查URL是否有效（服务器返回200状态码）
     */
    private boolean isUrlValid(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("HEAD"); // 只发送HEAD请求，减少数据传输
            connection.setConnectTimeout(5000); // 5秒连接超时
            connection.setReadTimeout(5000);    // 5秒读取超时
            connection.setInstanceFollowRedirects(true); // 跟随重定向
            return connection.getResponseCode() == 200;
        } catch (Exception e) {
            return false; // 连接失败或状态码非200，视为无效
        }
    }

    /**
     * 将相对路径转换为完整URL
     */
    private String resolveUrl(URL baseUrl, String relativePath) throws MalformedURLException {
        if (relativePath.startsWith("http://") || relativePath.startsWith("https://")) {
            return relativePath; // 已为绝对路径
        }
        return new URL(baseUrl, relativePath).toString(); // 基于基础URL解析相对路径
    }
}
